package com.ruoyi.rulengine.service.impl;

import com.ruoyi.iotcommon.domain.DeviceDataMessage;
import com.ruoyi.rulengine.domain.Rule;
import com.ruoyi.rulengine.domain.RuleAction;
import com.ruoyi.rulengine.domain.RuleCondition;
import com.ruoyi.rulengine.evaluator.RuleConditionEvaluator;
import com.ruoyi.rulengine.handler.RuleActionFactory;
import com.ruoyi.rulengine.service.IRuleEngineService;
import jakarta.annotation.Resource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

// 该文件无用，当时写的思路，请使用AsyncRuleEngineServiceImpl
//@Service
public class RuleEngineServiceImpl implements IRuleEngineService {

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Resource
    private RuleConditionEvaluator evaluator;


    @Resource
    RuleActionFactory ruleActionFactory;

    /**
     * 评估规则并执行动作
     *
     * @param rules      规则列表
     * @param deviceData 设备上报数据
     */
    public void evaluateRules(List<Rule> rules, DeviceDataMessage deviceData) {
        for (Rule rule : rules) {
            boolean isMatched = evaluateConditions(rule.getConditions(), rule.getLogical(), deviceData);
            if (isMatched) {
                executeActions(rule.getActions(), deviceData);
            }
        }
    }

    /**
     * 评估条件列表
     *
     * @param conditions 条件列表
     * @param logic      条件逻辑（AND 或 OR）
     * @param deviceData 设备上报数据
     * @return 是否满足条件
     */
    public boolean evaluateConditions(List<RuleCondition> conditions, String logic, DeviceDataMessage deviceData) {
        if ("AND".equals(logic)) {
            // 所有条件都必须满足
            return conditions.stream().allMatch(condition -> evaluator.evaluate(condition, deviceData));
        } else if ("OR".equals(logic)) {
            // 任意条件满足即可
            return conditions.stream().anyMatch(condition -> evaluator.evaluate(condition, deviceData));
        } else {
            throw new IllegalArgumentException("不支持的条件逻辑: " + logic);
        }
    }


    @Override
    public void executeActions(List<RuleAction> actions, DeviceDataMessage deviceData) {
        for (RuleAction action : actions) {
            CompletableFuture.runAsync(() -> ruleActionFactory.getHandler(action.getType()).execute(action), taskExecutor);
        }
    }
}
